import Dialog from '@vant/weapp/dialog/dialog';
import api from '../../api/index';
import { encrypt } from '../../utils/util';
const defaultAvatarUrl = 'https://gw.alicdn.com/imgextra/i2/O1CN01NIImHH1oddTwannmR_!!6000000005248-2-tps-200-200.png'
Page({
  data: {
    zIndex: -1,
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      userName: '',
    },
    show: false,
    popupForm: {
      oldPassword: '',
      newPassword: ''
    }
  },
  // 暂时不支持设置头像
  // onChooseAvatar(e: any) {
  //   const { avatarUrl } = e.detail
  //   const { nickName } = this.data.userInfo
  //   this.setData({
  //     "userInfo.avatarUrl": avatarUrl,
  //     hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
  //   })
  // }
  onModifyClick(e: any) {
    this.setData({
      show: true,
      zIndex: 2
    });
  },
  onPhoneClick(e: any) {
    Dialog.alert({
      title: '管理员联系方式',
      message: '当出现错误上报等无法挽回的错误操作的时候请及时联系管理员。\n\n联系号码：16666666666',
    }).then(() => {
      // on close
    });
  },
  onConfirm() {
    const app = getApp();
    const userNo = app.globalData.userInfo.userId;
    const _ = this;
    console.log(this.data.popupForm);

    api.updatePassword({
      userNo,
      oldPassword: encrypt(_.data.popupForm.oldPassword).toString(),
      password: encrypt(_.data.popupForm.newPassword).toString()
    }).then(res => {
      _.setData({
        show: false,
        zIndex: -1
      });
      if (res.status === 200) {
        Dialog.alert({
          title: '修改成功',
          message: '请重新登录',
          beforeClose: this.beforeClose
        })
      } else if (res.status === 201) {
        Dialog.alert({
          title: '修改失败',
          message: '密码错误'
        }).then(() => {
          // on confirm
        })
      }
    })
  },
  onCancel() {
    this.setData({
      show: false,
      zIndex: -1
    })
  },
  onLogout() {
    api.logout().then(res => {
      const app = getApp();
      console.log(app);

      app.globalData = {
        sites: [],
        isLogin: false,
        userInfo: {
          userId: '',
          userName: '',
          manageSites: [],
          phone: ''
        }
      };
      wx.redirectTo({
        url: '../login/login'
      })
      wx.removeStorageSync('token')
    });
  },
  onLoad() {
    const app = getApp();
    this.setData({ userInfo: { userName: app.globalData.userInfo.userName } })
    if (!app.globalData.isLogin) {
      wx.redirectTo({
        url: '/pages/login/login',
        success: () => {
          console.log('重定向到登录页成功');
        },
        fail: (err) => {
          console.log('重定向到登录页失败', err);
        }
      });
    }
  },
  /**
   * 对话框确认按钮异步方法
   * */
  beforeClose(action: string) {
    return new Promise((resolve) => {
      api.logout().then(res => {
        const app = getApp();
        app.globalData = {
          sites: [],
          isLogin: false,
          userInfo: {
            userId: '',
            userName: '',
            manageSites: [],
            phone: ''
          }
        }
        resolve(true);
        this.setData({
          show: false,
          zIndex: -1
        });
        wx.removeStorageSync('token')
        wx.navigateTo({
          url: '../login/login'
        })
      });
    });
  },
  onOldPasswordChange(e: any) {
    this.setData({
      popupForm: {
        oldPassword: e.detail,
        newPassword: this.data.popupForm.newPassword
      }
    })
  },
  onNewPasswordChange(e: any) {
    this.setData({
      popupForm: {
        newPassword: e.detail,
        oldPassword: this.data.popupForm.oldPassword
      }
    })
  },
  onInfoClick() {
    const app = getApp();
    const userInfo = app.globalData.userInfo;
    let manageSitesInfo = '';
    userInfo.manageSites.forEach(site => {
      manageSitesInfo += site.siteName;
      manageSitesInfo += ','
    })
    manageSitesInfo = manageSitesInfo.slice(0, -1);
    return Dialog.alert({
      title: '个人信息',
      message: `姓名：${userInfo.userName}\n联系方式：${userInfo.phone}\n用户名：${userInfo.userId}${manageSitesInfo === '' ? '' : `\n负责的渔场：${manageSitesInfo}`}`
    }).then(() => {

    })
  },
})
